package com.lee.webapp.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.io.*;

@Service("DataService")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class DataService {

    protected Logger log = LoggerFactory.getLogger(this.getClass());

    public static final String _PATH_KEY = "my_web_app";
    private String path = System.getenv(_PATH_KEY);

    public String getData() {

        BufferedReader reader = null;
        try {
            validatePath();

            reader = new BufferedReader(new FileReader(path));
            StringBuilder sb = new StringBuilder();
            String line = null;
            String ls = System.getProperty("line.separator");
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append(ls);
            }
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        } catch (Throwable ex) {
            log.error("文件访问失败", ex);
            return "[]";
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error("文件没能关闭", e);
                }
            }
        }
    }

    public void writeData(String data) {
        BufferedWriter out = null;
        try {
            validatePath();

            out = new BufferedWriter(new FileWriter(path));
            out.write(data);
        } catch (Throwable ex) {
            log.error("文件访问失败", ex);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("文件没能关闭", e);
                }
            }
        }
    }

    private void validatePath() throws Throwable {
        if (path == null) {
            String msg = "路径环境变量不能为空";
            log.error(msg);
            throw new Exception(msg);
        }
        File file = new File(path);
        if (!file.exists()) {
            String msg = "数据文件不存在";
            log.error(path);
            log.error(msg);
            throw new Exception(msg);
        }
    }
}
